package com.example.lyl.yuejian.view;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.format.DateFormat;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.lyl.yuejian.R;
import com.example.lyl.yuejian.bean.ModifyUserInfoResultBean;
import com.example.lyl.yuejian.bean.NotifyEventBean;
import com.example.lyl.yuejian.net.NetTool;
import com.example.lyl.yuejian.util.ImageUtil;
import com.example.lyl.yuejian.util.SharePreferenceUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ModifyUserInfoActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.nan)
    CheckBox nan;
    @BindView(R.id.nv)
    CheckBox nv;
    @BindView(R.id.telephone)
    EditText telephone;
    @BindView(R.id.adress)
    EditText adress;
    @BindView(R.id.qudxg_btn)
    Button qudxgBtn;

    String sex = "男";
    @BindView(R.id.xztx_btn)
    Button xztxBtn;
    @BindView(R.id.txIv)
    ImageView txIv;

    private final int CAMERACUP = 57;
    private final int ALBUMCUP = 58;
    private final int CUPREQUEST = 102;
    Uri imageuri;
    private String picPath;
    private File outImage;
    private Bitmap bitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_user_info);

        ButterKnife.bind(this);
        toolbar.setTitle("修改用户信息");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //是左上角按键出现
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        nan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == false && nv.isChecked() == false) {
                    nan.setChecked(true);
                }

                if (isChecked == true && nv.isChecked() == true) {
                    nv.setChecked(false);
                }
            }
        });

        nv.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == false && nan.isChecked() == false) {
                    nv.setChecked(true);
                }
                if (isChecked == true && nv.isChecked() == true) {
                    nan.setChecked(false);
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                EventBus.getDefault().post(new NotifyEventBean("刷新用户信息"));
                finish();
                break;
        }
        return true;
    }

    @OnClick({R.id.qudxg_btn, R.id.xztx_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.qudxg_btn:
                if (nv.isChecked() == true) {
                    sex = "男";
                } else {
                    sex = "女";
                }
                File file = new File(picPath);

                final RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);

                MultipartBody.Part body =
                        MultipartBody.Part.createFormData("img", file.getName(), requestFile);


                NetTool.getInstance().getApi().modifyUserInfoRequest(
                        SharePreferenceUtils.getInt(ModifyUserInfoActivity.this, "uid", 0), sex, telephone.getText().toString(),
                        adress.getText().toString(), body).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<ModifyUserInfoResultBean>() {
                            @Override
                            public void accept(ModifyUserInfoResultBean modifyUserInfoResultBean) throws Exception {
                                if (modifyUserInfoResultBean.getCode().equals("1")) {
                                    Toast.makeText(ModifyUserInfoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(ModifyUserInfoActivity.this, modifyUserInfoResultBean.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                throwable.printStackTrace();
                                Toast.makeText(ModifyUserInfoActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                            }
                        });
                break;
            case R.id.xztx_btn:
                //点击剪裁按钮
                new AlertDialog.Builder(ModifyUserInfoActivity.this).setItems(new String[]{"拍摄", "从相册选择"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                String sdPath = getExternalCacheDir().getPath();
                                String name = new DateFormat().format("yyyyMMddhhmmss",
                                        Calendar.getInstance(Locale.CHINA)) + ".jpg";
                                picPath = sdPath + "/" + name;

                                outImage = new File(picPath);


                                if (Build.VERSION.SDK_INT >= 24) {
                                    imageuri = FileProvider.getUriForFile(ModifyUserInfoActivity.this, "com.example.lyl.yuejian", outImage);
                                } else {
                                    imageuri = Uri.fromFile(outImage);
                                }

                                Intent intent = new Intent();
                                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);

                                startActivityForResult(intent, CAMERACUP);


                                break;
                            case 1:
                                Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
                                albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                startActivityForResult(albumIntent, ALBUMCUP);
                                break;
                        }
                    }
                }).create().show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CAMERACUP:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri inputUri = FileProvider.getUriForFile(ModifyUserInfoActivity.this, "com.example.lyl.yuejian", outImage);
                        startPhotoZoom(inputUri);
                    } else {
                        Uri inputUri = Uri.fromFile(outImage);
                        startPhotoZoom(inputUri);
                    }
                }
                break;
            case ALBUMCUP:
                if (resultCode == RESULT_OK) {
                    picPath = ImageUtil.getPath(ModifyUserInfoActivity.this, data.getData());
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri inputUri = FileProvider.getUriForFile(ModifyUserInfoActivity.this, "com.example.lyl.yuejian", new File(picPath));
                        startPhotoZoom(inputUri);
                    } else {
                        Uri inputUri = Uri.fromFile(new File((picPath)));
                        startPhotoZoom(inputUri);
                    }
                }
                break;

            case CUPREQUEST:
                if (data == null) {
                    return;
                }
                setImageToView(data);
                break;
        }
    }

    private void setImageToView(Intent data) {

        Bundle bundle = data.getExtras();
        if (bundle != null) {
            bitmap = bundle.getParcelable("data");
            txIv.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "bundle空", Toast.LENGTH_SHORT).show();
        }
    }

    private void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            intent.putExtra("noFaceDetection", false);//去除默认的人脸识别，否则和剪裁匡重叠
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        }

        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());// 图片格式

        startActivityForResult(intent, CUPREQUEST);
    }
}
